<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="80px"
      v-show="showSearch"
      size="small"
    >
      <el-form-item label="项目编号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="pdfList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column label="项目编号" prop="no" width="120" />
      <el-table-column
        label="检测项目"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="受检单位"
        prop="company"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="上传日期" prop="created_at" width="160">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.created_at, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "上传成功" : "未上传" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="text">查看二维码</el-button>
          <el-button size="mini" type="text">下载二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="no">
          <el-input v-model="form.no" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="检测项目" prop="name">
          <el-input v-model="form.name" placeholder="请输入检测项目" />
        </el-form-item>
        <el-form-item label="受检单位" prop="company">
          <el-input v-model="form.company" placeholder="请输入受检单位" />
        </el-form-item>
        <el-form-item label="上传PDF" prop="pdfFile">
          <el-upload
            ref="uploadRef"
            :http-request="customUpload"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            accept=".pdf"
            :limit="1"
            :auto-upload="true"
            :on-change="handleFileChange"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传PDF文件，且不超过100MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios"; // Import axios for HTTP requests
import { listPdf, getPdf, addPdf, updatePdf, delPdf } from "@/api/system/pdf";

export default {
  name: "PdfManager",
  data() {
    return {
      loading: false,
      total: 0,
      pdfList: [],
      open: false,
      title: "",
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      fileList: [],
      id: "", // For upload ID
      saveFileName: "", // For save_file_name
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: undefined,
        created_at: undefined,
      },
      form: {
        no: "",
        name: "",
        company: "",
        pdfFile: null, // Store the uploaded file URL or null
      },
      rules: {
        no: [{ required: true, message: "项目编号不能为空", trigger: "blur" }],
        name: [
          { required: true, message: "检测项目不能为空", trigger: "blur" },
        ],
        company: [
          { required: true, message: "受检单位不能为空", trigger: "blur" },
        ],
        pdfFile: [
          { required: true, message: "请上传PDF文件", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // Validate file before upload
    beforeUpload(file) {
      const isPDF = file.type === "application/pdf";
      const isLt100M = file.size / 1024 / 1024 < 100; // Check if file is less than 100MB

      if (!isPDF) {
        this.$modal.msgError("只能上传PDF文件");
        return false;
      }
      if (!isLt100M) {
        this.$modal.msgError("文件大小不能超过100MB");
        return false;
      }
      return true;
    },

    // Handle file selection/change
    handleFileChange(file, fileList) {
      this.fileList = fileList; // Update file list
      if (file.raw) {
        this.id = `pdf-${Date.now()}`; // Generate unique ID (modify as needed)
        this.saveFileName = file.name; // Use original file name
        this.form.pdfFile = file.raw; // Store raw file temporarily
      } else {
        this.id = "";
        this.saveFileName = "";
        this.form.pdfFile = null;
      }
    },

    // Custom upload function
    async customUpload(options) {
      const formData = new FormData();
      formData.append("file", options.file); // Append the file
      formData.append("id", this.id || `pdf-${Date.now()}`); // Ensure ID is set
      formData.append("save_file_name", this.saveFileName || options.file.name); // Ensure save_file_name is set

      try {
        const response = await axios.post("/dev-api/upload/pdf", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        options.onSuccess(response.data); // Trigger success handler
      } catch (error) {
        options.onError(error); // Trigger error handler
      }
    },

    // Handle successful upload
    handleUploadSuccess(response, file, fileList) {
      if (response.url && response.message) {
        this.$modal.msgSuccess(response.message);
        this.form.pdfFile = response.url; // Store the uploaded file URL
        this.fileList = [{ name: file.name, url: response.url }]; // Update file list
      } else {
        this.$modal.msgError("上传成功，但返回数据格式不正确");
        this.form.pdfFile = null;
        this.fileList = [];
      }
    },

    // Handle upload error
    handleUploadError(error) {
      console.error("Upload error:", error);
      const errorMsg = error.response?.data?.error || "文件上传失败，请重试";
      this.$modal.msgError(errorMsg);
      this.form.pdfFile = null;
      this.fileList = [];
      this.$refs.uploadRef.clearFiles();
    },

    // Submit form
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const data = {
            no: this.form.no,
            name: this.form.name,
            company: this.form.company,
            ossurl: this.form.pdfFile, // Use the uploaded file URL
          };

          const api = this.form.id ? updatePdf : addPdf;
          api(data)
            .then(() => {
              this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            })
            .catch((error) => {
              this.$modal.msgError("操作失败，请重试");
              console.error("Error submitting form:", error);
            });
        }
      });
    },

    // Fetch PDF list
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (params.created_at && params.created_at.length === 2) {
        params.beginTime = params.created_at[0];
        params.endTime = params.created_at[1];
      }
      delete params.created_at;

      listPdf(params)
        .then((res) => {
          this.pdfList = res.rows || [];
          this.total = res.total || 0;
          this.loading = false;
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
          this.loading = false;
        });
    },

    // Handle search query
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // Reset search query
    resetQuery() {
      this.queryParams.no = undefined;
      this.queryParams.created_at = undefined;
      this.handleQuery();
    },

    // Handle table selection change
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = selection.length === 0;
    },

    // Open add dialog
    handleAdd() {
      this.reset();
      this.title = "新增PDF";
      this.open = true;
    },

    // Open update dialog
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getPdf(id).then((res) => {
        this.form = {
          id: res.data.id,
          no: res.data.no,
          name: res.data.name,
          company: res.data.company,
          pdfFile: res.data.ossurl || null,
        };
        this.fileList = res.data.ossurl
          ? [{ name: res.data.name, url: res.data.ossurl }]
          : [];
        this.id = res.data.id || "";
        this.saveFileName = res.data.name || "";
        this.open = true;
        this.title = "修改PDF";
      });
    },

    // Handle delete
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("确认删除所选PDF吗？")
        .then(() => delPdf(ids))
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {});
    },

    // Cancel dialog
    cancel() {
      this.open = false;
      this.reset();
    },

    // Reset form
    reset() {
      this.form = {
        id: undefined,
        no: "",
        name: "",
        company: "",
        pdfFile: null,
      };
      this.fileList = [];
      this.id = "";
      this.saveFileName = "";
      this.resetForm("formRef");
      this.$refs.uploadRef && this.$refs.uploadRef.clearFiles();
    },
  },
};
</script>

<style scoped>
/* Add any custom styles if needed */
.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
